package com.lxit.cms.action.admin.assist;

import static com.lxit.common.page.SimplePage.cpn;
import static com.lxit.core.manager.AuthenticationMng.AUTH_KEY;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lxit.cms.entity.assist.CmsGuestbook;
import com.lxit.cms.entity.assist.CmsGuestbookCtg;
import com.lxit.cms.entity.assist.CmsGuestbookExt;
import com.lxit.cms.entity.main.CmsSite;
import com.lxit.cms.entity.main.CmsUser;
import com.lxit.cms.manager.assist.CmsGuestbookCtgMng;
import com.lxit.cms.manager.assist.CmsGuestbookMng;
import com.lxit.cms.manager.main.CmsLogMng;
import com.lxit.cms.web.CmsUtils;
import com.lxit.cms.web.WebErrors;
import com.lxit.common.page.Pagination;
import com.lxit.common.web.CookieUtils;
import com.lxit.common.web.RequestUtils;
import com.lxit.common.web.session.SessionProvider;
import com.lxit.core.entity.Authentication;
import com.lxit.core.manager.AuthenticationMng;

@Controller
public class CmsGuestbookAct {
	//sss 系统定时延时的常量设置 
	private static final int INTERVAL = 3;
	private static final Logger log = LoggerFactory
			.getLogger(CmsGuestbookAct.class);
	
	@RequestMapping("/guestbook/v_list.do")
	public String list(Integer queryCtgId, Boolean queryRecommend,
			Boolean queryChecked, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		Pagination pagination = manager.getPage(site.getId(), queryCtgId,
				queryRecommend, queryChecked, true, false, cpn(pageNo),
				CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("pageNo", pagination.getPageNo());
		return "guestbook/list";
	}
	
	@RequestMapping("/guestbook/v_add.do")
	public String add(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		List<CmsGuestbookCtg> ctgList = cmsGuestbookCtgMng
				.getList(site.getId());
		model.addAttribute("ctgList", ctgList);
		return "guestbook/add";
	}

	@RequestMapping("/guestbook/v_edit.do")
	public String edit(Integer id, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CmsGuestbook cmsGuestbook = manager.findById(id);
		List<CmsGuestbookCtg> ctgList = cmsGuestbookCtgMng
				.getList(site.getId());

		List<CmsUser> userList = new LinkedList<CmsUser>();
		for (CmsUser cmsUser : cmsGuestbook.getCtg().getUserSet()) {
			userList.add(cmsUser);
		}
		String objectArray = "";
		objectArray += "[";
		for (int i = 0; i < ctgList.size(); i++) {
			CmsGuestbookCtg cmsGuestbookCtg = ctgList.get(i);
			Set<CmsUser> cmsUserSet = cmsGuestbookCtg.getUserSet();
			Object[]  array= cmsUserSet.toArray();
			for (int j = 0; j <array.length; j++) {
				objectArray += "{ctgId:" + cmsGuestbookCtg.getId();
				CmsUser cmsUser =(CmsUser) array[j];
				objectArray += ",uId:" + cmsUser.getId() + ",uName:'"
						+ cmsUser.getUsername() + "'";
				objectArray += "}";
				if (j !=array.length - 1) {
					objectArray += ",";
				}
			}
			if (i != ctgList.size() - 1) {
				objectArray += ",";
			}
		}
		objectArray += "]";
		CmsUser cmsUser = new CmsUser();
		CmsGuestbookCtg cmsGuestbookCtg = new CmsGuestbookCtg();
		cmsGuestbook.setChecked(false);
		model.addAttribute("cmsGuestbook", cmsGuestbook);
		model.addAttribute("ctgList", ctgList);
		model.addAttribute("userList", userList);
		model.addAttribute("cmsUser", cmsUser);
		model.addAttribute("cmsGuestbookCtg", cmsGuestbookCtg);
		model.addAttribute("objectArray", objectArray);
		model.addAttribute("pageNo", pageNo);

		return "guestbook/edit";
	}

	@RequestMapping("/guestbook/o_save.do")
	public String save(CmsGuestbook bean, CmsGuestbookExt ext, Integer ctgId,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		String ip = RequestUtils.getIpAddr(request);
		bean = manager.save(bean, ext, ctgId, ip);
		log.info("save CmsGuestbook id={}", bean.getId());
		cmsLogMng.operating(request, "cmsGuestbook.log.save",
				"id=" + bean.getId() + ";title=" + bean.getTitle());
		return "redirect:v_list.do";
	}

	@RequestMapping("/guestbook/o_update.do")
	public String update(Integer queryCtgId, Boolean queryRecommend,
			Boolean queryChecked, CmsGuestbook bean, CmsGuestbookExt ext,
			Integer ctgId, Integer pageNo, HttpServletRequest request,
			ModelMap model, Integer userId, String isReply) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if (!"false".equals(isReply)) {
			bean.setReplayTime(new Date());
		}
		if (userId == null) {
			bean.setAdmin(null);
		} else {
			bean.setAdmin(new CmsUser(userId));
		}
		bean.setAssignDate(new Date());
		bean = manager.update(bean, ext, ctgId);
		log.info("update CmsGuestbook id={}.", bean.getId());
		cmsLogMng.operating(request, "cmsGuestbook.log.update",
				"id=" + bean.getId() + ";title=" + bean.getTitle());
		if(!"false".equals(isReply)){
			String s = dangList(queryCtgId, queryRecommend, queryChecked, pageNo, request, model);
			return s;
		}
		return list(queryCtgId, queryRecommend, queryChecked, pageNo, request,
				model);
	}

	@RequestMapping("/guestbook/o_delete.do")
	public String delete(Integer queryCtgId, Boolean queryRecommend,
			Boolean queryChecked, Integer[] ids, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CmsGuestbook[] beans = manager.deleteByIds(ids);
		for (CmsGuestbook bean : beans) {
			log.info("delete CmsGuestbook id={}", bean.getId());
			cmsLogMng.operating(request, "cmsGuestbook.log.delete", "id="
					+ bean.getId() + ";title=" + bean.getTitle());
		}
		return list(queryCtgId, queryRecommend, queryChecked, pageNo, request,
				model);
	}

	private WebErrors validateSave(CmsGuestbook bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		CmsSite site = CmsUtils.getSite(request);
		bean.setSite(site);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		CmsSite site = CmsUtils.getSite(request);
		if (vldExist(id, site.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		CmsSite site = CmsUtils.getSite(request);
		if (vldExist(id, site.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		CmsSite site = CmsUtils.getSite(request);
		if (errors.ifEmpty(ids, "ids")) {
			return errors;
		}
		for (Integer id : ids) {
			vldExist(id, site.getId(), errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, Integer siteId, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		CmsGuestbook entity = manager.findById(id);
		if (errors.ifNotExist(entity, CmsGuestbook.class, id)) {
			return true;
		}
		if (!entity.getSite().getId().equals(siteId)) {
			errors.notInSite(CmsGuestbook.class, id);
			return true;
		}
		return false;
	}

	@RequestMapping("/guestbook/p_edit.do")
	public String dangEdit(Integer id, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CmsGuestbook cmsGuestbook = manager.findById(id);
		List<CmsGuestbookCtg> ctgList = cmsGuestbookCtgMng
				.getList(site.getId());

		List<CmsUser> userList = new LinkedList<CmsUser>();
		for (CmsUser cmsUser : cmsGuestbook.getCtg().getUserSet()) {
			userList.add(cmsUser);
		}
		
		Date assignDate = cmsGuestbook.getAssignDate();
    boolean ifDelay = false;
    if(assignDate != null){
      DateTime assignTime = new DateTime(assignDate);
      DateTime currentTime = new DateTime(new Date());
      DateTime assignDates = assignTime.plusDays(INTERVAL);
      int result = assignDates.compareTo(currentTime);
      if(result < 0 && cmsGuestbook.getReplayTime()==null){
        ifDelay = true;
      }
    }
    
		CmsUser cmsUser = new CmsUser();
		cmsGuestbook.setChecked(false);
		model.addAttribute("cmsGuestbook", cmsGuestbook);
		model.addAttribute("ctgList", ctgList);
		model.addAttribute("userList", userList);
		model.addAttribute("cmsUser", cmsUser);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("userId", cmsGuestbook.getAdmin().getId());
		model.addAttribute("ifDelay", ifDelay);
		return "guestbook/dang_edit";
	}

	@RequestMapping("/guestbook/p_list.do")
	public String dangList(Integer queryCtgId, Boolean queryRecommend,
			Boolean queryChecked, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		String authId = (String) session.getAttribute(request, AUTH_KEY);
		Authentication auth = authMng.retrieve(authId);
		int userId = auth.getUid();

		Pagination pagination = manager.getDangPage(userId, site.getId(),
				queryCtgId, queryRecommend, queryChecked, true, false,
				cpn(pageNo), CookieUtils.getPageSize(request));

		model.addAttribute("pagination", pagination);
		model.addAttribute("pageNo", pagination.getPageNo());
		return "guestbook/dang_list";
	}

	@Autowired
	private CmsGuestbookCtgMng cmsGuestbookCtgMng;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private CmsGuestbookMng manager;
	@Autowired
	private AuthenticationMng authMng;
	@Autowired
	private SessionProvider session;
}